package jupitermouse.site.juc.demo.thread;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * <p>
 *     在子线程中，可以获取到父线程的InheritableThreadLocal类型变量的值，而不能获取到ThreadLocal类型变量的值
 * </p>
 *
 * @author jupiter
 */
public class InheritableThreadLocalApp {
    public static void main(String[] args) throws InterruptedException {
        test();
    }
    static InheritableThreadLocal<Value> threadLocal = new InheritableThreadLocal<>();

    static void test() throws InterruptedException {

        Thread.currentThread().setName("main-thread");

        //主线程设置一个值
        threadLocal.set(new Value("dhyTest"));

        //运行子线程
        Thread childThread = new Thread(new ChildThread(), "child-thread");
        childThread.start();

        //主线成等待子线程运行完，以便观察主线中设置的值是否被子线程成功修改
        childThread.join();

        System.out.println("父线程获取到的最终的值：" + threadLocal.get());

    }

    static class ChildThread implements Runnable {
        @Override
        public void run() {
            Value value = threadLocal.get();
            System.out.println("子线程中直接调用get方法获取父线程的值，value:" + value.getData());
            value.setData(value.getData() + "---子线程对父线程的值做了修改");
        }
    }
}
@Data
@AllArgsConstructor
class Value{
    private String data;
}

